package com.nmsl.service;

import com.nmsl.domain.TyPatient;
import com.nmsl.domain.TyRegistrationManagement;
import com.nmsl.mapper.TyPatientMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TyPatientService {
    @Autowired
    private TyPatientMapper tyPatientMapper;
    public int updateByPrimaryKeySelective(TyPatient record) {
        return tyPatientMapper.updateByPrimaryKeySelective(record);
    }

    public TyPatient selectByPatientId(Integer patientId) {
        return tyPatientMapper.selectByPatientId(patientId);
    }

    public TyPatient selectByPrimaryKey2(Integer patientId){
        return tyPatientMapper.selectByPrimaryKey2(patientId);
    }

    public int calculateWaitingCount(TyPatient currentPatient) {
        // 获取当前挂号记录（需确保列表不为空）
        List<TyRegistrationManagement> regList = currentPatient.getTyRegistrationManagementList();
        if (regList == null || regList.isEmpty()) {
            throw new RuntimeException("患者无有效挂号记录");
        }
        TyRegistrationManagement reg = regList.get(0);

        // 调用 Mapper 查询同一科室、医生、日期、时间段的未就诊记录
        List<TyPatient> waitingPatients = tyPatientMapper.selectAllPatientInTime(
                reg.getDepartmentId(),
                reg.getDoctorId(),
                reg.getRegistrationPeriod(),  // 关键：传入时间段参数
                reg.getRegistrationDate()
        );

        // 查找当前患者在列表中的位置
        for (int i = 0; i < waitingPatients.size(); i++) {
            if (waitingPatients.get(i).getPatientId().equals(currentPatient.getPatientId())) {
                return i; // 索引即为前面的人数
            }
        }
        return 0; // 未找到默认返回0
    }

    public TyPatient selectBalanceByPatientId(Integer patientId) {
        return tyPatientMapper.selectBalanceByPatientId(patientId);
    }

    public List<TyPatient> selectAllPatient() {
        return tyPatientMapper.selectAllPatient();
    }

}
